package com.example.idlefish.GoodsInfo

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.ActivityContract.GooddResultContract
import com.example.idlefish.GoodsInfo.ActivityContract.ToHomePageContract
import com.example.idlefish.GoodsInfo.parseGson.parseListGood
import com.example.idlefish.GoodsInfo.pojo.EaseGoodInfo
import com.example.idlefish.GoodsInfo.pojo.GoodEase
import com.example.idlefish.GoodsInfo.pojo.ListGood
import com.example.idlefish.MyAccount.contract.HomepageContract
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.ApplicationConst.server_ip
import com.example.idlefish.R
import com.example.idlefish.databinding.ActivityKindGoodListBinding
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class KindGoodListActivity : AppCompatActivity() {
    private lateinit var binding:ActivityKindGoodListBinding
    //传入信息
    private lateinit var  defaultBitmap: Bitmap
    private var infos = ArrayList<ListGood>()
    private var pics = ArrayList<Bitmap>()
    //缓存
    private val imageMap = mutableMapOf<Int, ArrayList<Bitmap>>()
    //Adapter专用 !!!
    private  var goodList = ArrayList<EaseGoodInfo>()
    //分类
    private var classifyList = ArrayList<String>()
    private var selectIndex = -1
    private val homepageLauncher = registerForActivityResult(HomepageContract()) { result ->

    }
    private val goodContentLauncher = registerForActivityResult(GooddResultContract()){
            result->

    }

    private lateinit var goodListAdapter:GoodListAdapter
    private lateinit var goodClassifyAdapter: ClassifyAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityKindGoodListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.loadingtv3.visibility = View.VISIBLE
        binding.loading3.show()
        //属性的adapter
        imageMap.clear()
        defaultBitmap = BitmapFactory.decodeResource(resources, R.drawable.null_product)
        val layoutManager0 = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        binding.goodClassify.layoutManager = layoutManager0
        goodClassifyAdapter = ClassifyAdapter(classifyList)
        binding.goodClassify.adapter = goodClassifyAdapter

        //商品列表的adapter
        val layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.goodList.layoutManager = layoutManager
        goodListAdapter = GoodListAdapter(goodList)
        binding.goodList.adapter = goodListAdapter
        Init()
        binding.goodOrderReturn.setOnClickListener {
            finish()
        }

    }
    private class GoodListViewHolder(view: View): RecyclerView.ViewHolder(view){
        val elemGoodImage = view.findViewById<ImageView>(R.id.elemGoodImage)
        val elemGoodName = view.findViewById<TextView>(R.id.elemGoodName)
        val elemGoodPrice = view.findViewById<TextView>(R.id.elemGoodPrice)
        val elemSellerAvatar = view.findViewById<ImageView>(R.id.elemSellerAvatar)
        val elemSellerName = view.findViewById<TextView>(R.id.elemSellerName)
        val userClick = view.findViewById<LinearLayout>(R.id.userClick)
    }
    private inner class GoodListAdapter(val lstGood:ArrayList<EaseGoodInfo>):RecyclerView.Adapter<GoodListViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoodListViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.good_list_elem_layout, parent, false)
            val viewHolder = GoodListViewHolder(view)
            viewHolder.userClick.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val userId = goodList[index].userId
                homepageLauncher.launch(userId)
            }
            viewHolder.elemGoodImage.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val goodId = goodList[index].goodId
                goodContentLauncher.launch(goodId)
            }
            viewHolder.elemGoodName.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val goodId = goodList[index].goodId
                goodContentLauncher.launch(goodId)
            }
            viewHolder.elemGoodPrice.setOnClickListener {
                val index = viewHolder.absoluteAdapterPosition
                val goodId = goodList[index].goodId
                goodContentLauncher.launch(goodId)
            }
            return viewHolder
        }

        override fun getItemCount(): Int {
            return lstGood.size
        }

        override fun onBindViewHolder(holder: GoodListViewHolder, position: Int) {
            val info = goodList[position]
            holder.elemGoodImage.setImageBitmap(imageMap[selectIndex]?.get(position) ?: defaultBitmap)
            holder.elemGoodPrice.text = "￥"+ info.price.toString()
            holder.elemGoodName.text = info.goodName
            holder.elemSellerName.text = info.userName
            holder.elemSellerAvatar.setImageBitmap(ApplicationConst.decodeBase64ToImage(applicationContext, info.userAvatar))
        }
    }
    private class ClassifyViewHolder(view:View):RecyclerView.ViewHolder(view){
        val classifyName = view.findViewById<TextView>(R.id.classifyName)
    }
    private inner class ClassifyAdapter(val lstClassify:ArrayList<String>):RecyclerView.Adapter<ClassifyViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClassifyViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.kind_good_classify_layout, parent, false)
            val viewHolder = ClassifyViewHolder(view)
            viewHolder.classifyName.setOnClickListener {
                viewHolder.classifyName.isSelected = true
                val index = viewHolder.absoluteAdapterPosition
                selectIndex = index
                goodList.clear()
                goodList.addAll(infos[index].goodInfo)
                if(!imageMap.containsKey(index))
                {
                    val innerList = ArrayList<Bitmap>()
                    for (tep2 in infos[index].goodInfo) {
                        val bitmap = ApplicationConst.decodeBase64ToImage(applicationContext, tep2.goodPic1)
                        if (bitmap != null) {
                            innerList.add(bitmap)
                        } else {
                            innerList.add(BitmapFactory.decodeResource(resources, R.drawable.null_product))
                        }
                    }
                    imageMap[index] = innerList
                }
                goodListAdapter.notifyDataSetChanged()
                goodClassifyAdapter.notifyDataSetChanged()
            }
            return viewHolder
        }

        override fun onBindViewHolder(holder: ClassifyViewHolder, position: Int) {
            holder.classifyName.text = lstClassify[position]
            holder.classifyName.isSelected = (position == selectIndex)
            if(selectIndex == position)
            {
                holder.classifyName.setTypeface(null, Typeface.BOLD)
                holder.classifyName.setTextColor(android.graphics.Color.BLACK)

            }
            else
            {
                holder.classifyName.setTypeface(null, Typeface.NORMAL)
                holder.classifyName.setTextColor(android.graphics.Color.DKGRAY)

            }
        }

        override fun getItemCount(): Int {
            return lstClassify.size
        }
    }
    fun Init()
    {
        //传入kind和name在contract里面!!!!!!!!!!!!!!!!!!111
        val kind = intent.getStringExtra("kind")?:"其他"
        val name = intent.getStringExtra("name")?:"分类"
        binding.tittle.text = name
        netForClassifyGood(kind, object : Callback{
            override fun onResponse(call: Call, response: Response) {
                Log.d("hello", "网络请求商品kindList成功")
                val responseData = response.body?.string().toString()
                infos.addAll(parseListGood.parseListGood(responseData))
                Log.i("商品kindList{}", infos.toString())
                for(tep in infos)
                {
                    classifyList.add(tep.classify)
                }
                if(classifyList.size > 0)
                {
                    goodList.clear()
                    goodList.addAll(infos[0].goodInfo)
                    selectIndex = 0
                }
                runOnUiThread {
                    goodClassifyAdapter.notifyDataSetChanged()
                    goodListAdapter.notifyDataSetChanged()
                    binding.loadingtv3.visibility = View.GONE
                    binding.loading3.hide()
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                Log.d("hello", "网络请求商品kindList失败")
                binding.loadingtv3.visibility = View.GONE
                binding.loading3.hide()
            }
        })
    }
    fun netForClassifyGood(kind:String, callback: Callback)
    {
        val client = OkHttpClient()
        val jsp = "http://$server_ip:8080/listGoodByKind?kind=${kind}"
        val request = Request.Builder()
            .url(jsp).get().build()
        client.newCall(request).enqueue(callback)
    }
}